package com.sailing.face.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sailing.face.dto.FaceImageResultDTO;
import com.sailing.face.dto.ResponseResult;
import com.sailing.face.entity.FaceAnalysisResult;
import com.sailing.face.entity.FaceAnalysisResultDetail;
import com.sailing.face.entity.ImportResult;
import com.sailing.face.entity.ImportResultDetail;
import com.sailing.face.service.FaceImageService;
import com.sailing.face.util.CommonTools;
import com.sailing.face.util.FaceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :fox
 * @version ：2017年11月6日12:47:41 类说明:人脸图片识别
 */
@Service
public class FaceImageServiceImpl implements FaceImageService{
	private static Logger logger = LoggerFactory
			.getLogger(FaceImageServiceImpl.class);

	@Value("${file.collect.path}")
	private String FILE_COLLECT_PATH;
	@Value("${file.app.url}")
	private String FILE_APP_URL;
	@Value("${face.repository.ids}")
	private String FACE_REPOSITORY_IDS;
	@Value("${face.repository.names}")
	private String FACE_REPOSITORY_NAMES;
	@Value("${faceServer.baseUrl}")
	private String baseUrl;
	@Value("${faceServer.login}")
	private String loginUrl;
	@Value("${faceServer.synchronized}")
	private String synchronizedUrl;
	@Value("${faceServer.retrieval}")
	private String retrievalUrl;
	@Value("${faceServer.image}")
	private String imageUrl;





	@Override
	public ResponseResult analysisFaceImage(String base64,String repositoryId) {
		ResponseResult r;
		try {
				String sessionId = "0";
				// 登录
				Map<String,String> loginJson = new HashMap<String,String>();
				loginJson.put("name", "admin");
				loginJson.put("password", "21232f297a57a5a743894a0e4a801fc3");
				String loginString = FaceUtil.postFaceMessage(
						JSON.toJSONString(loginJson),
						baseUrl+loginUrl, sessionId);
				JSONObject login = JSONObject.parseObject(loginString);
				int rtn = login.getIntValue("rtn");
				if (rtn == 0) {
					//sessionId = login.getIntValue("session_id");
					sessionId = login.getString("session_id");
					logger.debug("session_id", sessionId);
				} else {
					r = new ResponseResult(ResponseResult.RESPONSE_CODE_FAILD,
							"登录识别接口失败");
				}

				List<FaceImageResultDTO> faceImageResultDTOs = new ArrayList<FaceImageResultDTO>();

				// 导入原始图片
				JSONObject optionsJson = new JSONObject();
				optionsJson.put("max_faces_allowed", -1);
				JSONObject importJson = new JSONObject();
				importJson.put("options", optionsJson);
				importJson.put("picture_image_content_base64", base64.replaceAll("\r|\n", ""));
				String importResultString = FaceUtil
						.postFaceMessage(
								JSON.toJSONString(importJson),
								baseUrl+synchronizedUrl,
								sessionId);
				ImportResult importResult = JSONObject.parseObject(
						importResultString, ImportResult.class);
				if (importResult == null || (importResult.getRtn() != 0&&importResult.getRtn() != -4600)) {
					r = new ResponseResult(ResponseResult.RESPONSE_CODE_FAILD,
							"导入图片失败");
				}else if(importResult.getRtn() == -4600){
					return new ResponseResult(ResponseResult.EMPTY_DATA_FACE,
							"未检索人脸");
				} else {
					ImportResultDetail[] details = importResult.getResults();
					for (ImportResultDetail importResultDetail : details) {
						// 获取分析结果
						JSONObject analysisFaceJson = new JSONObject();
						String[] fields = { "face_image_id", "repository_id",
								"timestamp", "person_id", "name", "gender",
								"nation", "camera_id", "is_hit", "born_year",
								"similarity", "annotation", "picture_uri",
								"face_image_uri", "face_image_url" };
						analysisFaceJson.put("fields", fields);
						JSONObject contitionJson = new JSONObject();
						analysisFaceJson.put("condition", contitionJson);
						JSONObject retrievalJson = new JSONObject();
						retrievalJson.put("threshold", 0);
						retrievalJson.put("face_image_id",
								importResultDetail.getFace_image_id());
						List<String> ids = new ArrayList<String>();
						if(StringUtils.isEmpty(repositoryId)){
							String[] str = FACE_REPOSITORY_IDS.split(",");
							for(String s:str){
								ids.add(s);
							}
						}else{
							String[] str = repositoryId.split(",");
							for(String s:str){
								ids.add(s);
							}
						}
						retrievalJson.put("repository_ids", ids);


						analysisFaceJson.put("retrieval", retrievalJson);
						JSONObject orderJson = new JSONObject();
						orderJson.put("similarity", -1);
						analysisFaceJson.put("order", orderJson);
						analysisFaceJson.put("start", 0);
						analysisFaceJson.put("limit", 10);
						String analysisResultString = FaceUtil.postFaceMessage(
								JSON.toJSONString(analysisFaceJson),
								baseUrl+retrievalUrl, sessionId);
						FaceAnalysisResult analysisFaceResult = JSONObject
								.parseObject(analysisResultString,
										FaceAnalysisResult.class);
						if (analysisFaceResult != null
								&& analysisFaceResult.getRtn() == 0
								&& analysisFaceResult.getResults().length > 0) {
							//开始配置重点类型map字典
							Map<String,String> faceKey = null;
							String repositoryid[] = FACE_REPOSITORY_IDS.split(",");
							String repositoryName[] = FACE_REPOSITORY_NAMES.split(",");
							if((repositoryid.length==repositoryName.length)&&!repositoryid[0].equals("")&&!repositoryName[0].equals("")){
								faceKey = new HashMap<String,String>();
								for(int i=0 ; i<repositoryid.length ; i++){
									faceKey.put(repositoryid[i], repositoryName[i]);
								}
								logger.debug("人脸重点类型字典配置成功");
							}else{
								faceKey = new HashMap<String,String>();
								faceKey.put("err", "配置有误");
								logger.debug("人脸重点类型字典配置失败");
							}

							// 获取相似图片
							List<FaceAnalysisResultDetail> analysisFaceResultDetails = new ArrayList<FaceAnalysisResultDetail>();
							for (FaceAnalysisResultDetail analysisFaceResultDetail : analysisFaceResult
									.getResults()) {
								FaceUtil.downloadFaceImage(
												baseUrl+imageUrl,
												"uri_base64=" + CommonTools.encodeStr(analysisFaceResultDetail.getPicture_uri()).replace("\n","").replace("\r",""),
														sessionId,
												FILE_COLLECT_PATH + "/"
														+ analysisFaceResultDetail
														.getFace_image_id_str()
														+ ".jpg");
								analysisFaceResultDetail
										.setPicture_url(FILE_APP_URL +"?fileName="
												+ analysisFaceResultDetail
														.getFace_image_id_str()
												+ ".jpg");
								analysisFaceResultDetail.setPicture_uri("");
								if(!faceKey.containsKey("err")){
									analysisFaceResultDetail.setRepository_name(faceKey.get(analysisFaceResultDetail.getRepository_id()));
								}
								analysisFaceResultDetails
										.add(analysisFaceResultDetail);
							}

							FaceImageResultDTO faceImageResultDTO = new FaceImageResultDTO();
							faceImageResultDTO
									.setImportResultDetail(importResultDetail);
							faceImageResultDTO
									.setFaceAnalysisResultDetails(analysisFaceResultDetails);
							faceImageResultDTOs.add(faceImageResultDTO);
						}
					}

					if (faceImageResultDTOs.size() > 0) {
						r = new ResponseResult(
								ResponseResult.RESPONSE_CODE_SUCCESS, "检索成功",faceImageResultDTOs);
					} else {
						r = new ResponseResult(ResponseResult.EMPTY_DATA,
								"未检索到相似人脸");
					}

				}


		} catch (Exception e) {
			r = new ResponseResult(ResponseResult.RESPONSE_CODE_FAILD, "服务器异常");
		}
		return r;
	}
}
